package model;



import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LibrarySystem {
    private final Map<String, Resource> resources = new HashMap<>();
    private final Map<String, Borrower> borrowers = new HashMap<>();

    // 资源管理
    public void addResource(Resource resource) {
        resources.put(resource.getId(), resource);
    }

    public boolean removeResource(String resourceId) {
        Resource resource = resources.get(resourceId);
        if (resource != null && !resource.isBorrowed()) {
            resources.remove(resourceId);
            return true;
        }
        return false;
    }

    public Resource getResource(String resourceId) {
        return resources.get(resourceId);
    }

    public Collection<Resource> getAllResources() {
        return new ArrayList<>(resources.values());
    }

    // 新增：获取所有借阅者
    public Collection<Borrower> getAllBorrowers() {
        return new ArrayList<>(borrowers.values());
    }

    // 搜索功能
    public List<Resource> findResource(String query) {
        List<Resource> results = new ArrayList<>();
        String lowerQuery = query.toLowerCase();

        for (Resource resource : resources.values()) {
            if (resource.getTitle().toLowerCase().contains(lowerQuery) ||
                    resource.getId().toLowerCase().contains(lowerQuery)) {
                results.add(resource);
            }
        }
        return results;
    }

    //
    public void registerBorrower(Borrower borrower) {
        borrowers.put(borrower.getId(), borrower);
    }

    public Borrower getBorrower(String borrowerId) {
        return borrowers.get(borrowerId);
    }

    // 借阅操作借阅者管理
    public boolean borrowResource(String borrowerId, String resourceId) {
        Borrower borrower = borrowers.get(borrowerId);
        Resource resource = resources.get(resourceId);

        if (borrower == null || resource == null) return false;
        return borrower.borrowResource(resource);
    }

    // 归还操作借阅操作借阅者管理
    public boolean returnResource(String borrowerId, String resourceId) {
        Borrower borrower = borrowers.get(borrowerId);
        if (borrower == null) return false;
        return borrower.returnResource(resourceId);
    }
}
